package org.ofbiz.sys.utils;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ofbiz.base.util.Debug;


public final class ResponseUtils {

	/**
	 * 发送文本。使用UTF-8编码。
	 * 
	 * @param response
	 *            HttpServletResponse
	 * @param text
	 *            发送的字符串
	 */
	public static void renderText(HttpServletResponse response, String text) {
		render(response, "text/plain;charset=UTF-8", text);
	}

	/**
	 * 发送json。使用UTF-8编码。
	 * 
	 * @param response
	 *            HttpServletResponse
	 * @param text
	 *            发送的字符串
	 */
	public static void renderJson(HttpServletResponse response, String text) {
		render(response, "application/json;charset=UTF-8", text);
	}

	/**
	 * 发送xml。使用UTF-8编码。
	 * 
	 * @param response
	 *            HttpServletResponse
	 * @param text
	 *            发送的字符串
	 */
	public static void renderXml(HttpServletResponse response, String text) {
		render(response, "text/xml;charset=UTF-8", text);
	}

	/**
	 * 发送内容。使用UTF-8编码。
	 * 
	 * @param response
	 * @param contentType
	 * @param text
	 */
	public static void render(HttpServletResponse response, String contentType,
			String text) {
		response.setContentType(contentType);
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("access-control-allow-methods", "POST,PUT,GET,HEAD,OPTIONS,PATCH,DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
		response.setHeader("access-control-allow-credentials", "true");
		try {
			response.getWriter().write(text);
		} catch (IOException e) {
			Debug.logError(e.getMessage(), "ResponseUtils");
		}
	}
	
	public static void renderApiJson(HttpServletResponse response,
			HttpServletRequest request,ApiResponse apiResult) {
		response.setCharacterEncoding("UTF-8");
		if(apiResult.getResult().contains("uploadPath")&&apiResult.getResult().contains("fileName")){
			ResponseUtils.renderText(response, apiResult.toString());
		}else{
			ResponseUtils.renderJson(response, apiResult.toString());
		}
	}
	
	public static void renderApiUeditor(HttpServletResponse response,
			HttpServletRequest request,Map<String,Object> serviceResults,ApiResponse apiResult) {
		response.setCharacterEncoding("UTF-8");
		String str ="{\"result\":" + apiResult.getResult() +", \"state\":" + "\""+serviceResults.get("state")+"\"" + ", \"title\":" + "\""+serviceResults.get("title")+"\"" + ", \"url\":" + "\""+serviceResults.get("url")+"\"" + ", \"original\":" + "\""+serviceResults.get("original")+"\"" + ", \"message\":" + apiResult.getMessage() + ", \"code\":" + apiResult.getCode() + "}";
		ResponseUtils.renderText(response, str);
	}
}
